package com.eqdd.yiqidian.ui.discover.workdiary

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.eqdd.annotation.api.DataInjector
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.WorkDiaryTodayBean
import com.eqdd.yiqidian.bean.WorkDiaryUploadBean
import com.eqdd.yiqidian.http.HttpCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.ListHttpResult
import com.eqdd.yiqidian.kotlin.KotlinBaseActivity
import com.eqdd.yiqidian.service.LocationObservable
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.utils.SPUtil
import com.eqdd.yiqidian.widget.ChooseAlertView
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions.RxPermissions
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_work_diary_add.*
import kotlinx.android.synthetic.main.list_item_130.view.*
import org.jetbrains.anko.forEachChild
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.io.Serializable
import java.text.SimpleDateFormat
import java.util.*

/**
 * 新增工作日志
 * Created by jhj on 18-4-24.
 */
class WorkDiaryAddActivity : KotlinBaseActivity() {

    companion object {
        val TODAY = 100
        val TOMORROW = 101
    }

    lateinit var inflater: LayoutInflater
    private var location: String? = null
    private var displayType = 0
    private var subscribe: Disposable? = null
    private var paramBean: WorkDiaryUploadBean = WorkDiaryUploadBean()
    private var isUploadSuccess = false

    interface OnResultListener {
        fun callback(string: String)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_work_diary_add)
        super.onCreate(savedInstanceState)
        inflater = LayoutInflater.from(this)
        getLocation()
        initView()

        initTopBar("增加工作日志", "发布日志", View.OnClickListener {
            uploadData()
        })

        tv_add_today.onClick {
            startActivityForResult<WorkDiaryItemActivity>(TODAY, "type" to 0)
        }

        tv_add_tomorrow.onClick {
            startActivityForResult<WorkDiaryItemActivity>(TOMORROW, "type" to 1)
        }

        tv_inspiration.onClick {
            startActivityForResult<EditTextActivity>(1000, "title" to "今日感悟",
                    "tip" to "今日感悟", "content" to tv_inspiration.text.toString())
        }

        tv_location.onClick {
            getLocation()
        }

        tv_look_over.text = "仅自己和领导可见"
        tv_look_over.onClick {
            lookOver()
        }


    }

    fun initView() {
        val data = SPUtil.getParam(localClassName + user.uname) as? SaveDataBean
        val bean = Gson().fromJson<WorkDiaryUploadBean>(data?.workDiary, WorkDiaryUploadBean::class.java)
        if (bean != null) {
            bean.matter.forEach {
                val view = inflater.inflate(R.layout.list_item_130, layout_diary_today, false)
                val array = it.timeSlot.split("-")
                initItemData(view, array[0].trim(), array[1].trim(),
                        it.content, it.status, 0)
                layout_diary_today.addView(view)

            }

            bean.tomorrowMatter.forEach {
                val view = inflater.inflate(R.layout.list_item_130, layout_diary_tomorrow, false)
                val array = it.timeSlot.split("-")
                initItemData(view, array[0].trim(), array[1].trim(),
                        it.content, "", 1)

                layout_diary_tomorrow.addView(view)
            }
            tv_inspiration.text = data?.filling
            DataInjector.recoverData(this)
        }
    }


    override fun initData() {
        super.initData()
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
        OkGo.post<ListHttpResult<WorkDiaryTodayBean>>(HttpConfig.BASE_URL + HttpConfig.DIARY_TODAY)
                .params("userGuid", user.guid)
                .params("date", sdf.format(Date()))
                .execute(object : HttpCallBack<ListHttpResult<WorkDiaryTodayBean>>(this@WorkDiaryAddActivity) {
                    override fun onSuccess(response: Response<ListHttpResult<WorkDiaryTodayBean>>) {
                        val httpResult = response.body()
                        if (httpResult.status == 200 && httpResult.items.size > 0) {
                            httpResult.items.forEach {
                                var result = ""
                                val view = inflater.inflate(R.layout.list_item_130, layout_diary_plan, false)
                                view.tv_plan_label.text = "今日计划事项："
                                view.tv_plan.text = it.content
                                view.tv_time.text = it.timeSlot
                                view.onClick {
                                    initLimit(view.tv_result, object : OnResultListener {
                                        override fun callback(string: String) {
                                            result = string
                                        }
                                    })
                                }
                                view.tag = it.id.toString() + ":" + result
                                layout_diary_plan.addView(view)
                            }
                        }
                    }
                })


    }

    private fun uploadData() {
        if (tv_inspiration.text.isNullOrEmpty()) {
            toast("请输入今日感悟")
            return
        }

        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.DIARY_ADD)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params("departmentId", user.departId)
                .params("location", location)
                .params("jsonPara", getParams())
                .params("feeling", tv_inspiration.text.toString())
                .params("displayType", displayType)
                .execute(object : HttpCallBack<HttpResult<*>>(this@WorkDiaryAddActivity) {
                    override fun onSuccess(response: Response<HttpResult<*>>) {
                        val httpResult = response.body()
                        toast(httpResult.msg)
                        if (httpResult.status == 200) {
                            clearData()
                            isUploadSuccess = true
                        }
                        finish()
                    }
                })


    }

    private fun getParams(): String {
        paramBean.matter = arrayListOf()
        paramBean.tomorrowMatter = arrayListOf()
        paramBean.plan = arrayListOf()
        if (layout_diary_today.childCount > 0) {
            layout_diary_today.forEachChild {
                val bean = WorkDiaryUploadBean.MatterBean()
                bean.timeSlot = it.tv_time.text.toString()
                bean.content = it.tv_plan.text.toString()
                bean.status = it.tv_result.text.toString()
                paramBean.matter.add(bean)
            }
        }

        if (layout_diary_tomorrow.childCount > 0) {
            layout_diary_tomorrow.forEachChild {
                val bean = WorkDiaryUploadBean.TomorrowMatterBean()
                bean.timeSlot = it.tv_time.text.toString()
                bean.content = it.tv_plan.text.toString()
                paramBean.tomorrowMatter.add(bean)
            }
        }

        if (layout_diary_plan.childCount > 0) {
            layout_diary_plan.forEachChild {
                val bean = WorkDiaryUploadBean.PlanBean()
                val tag = it.tag as String
                val arrays = tag.split(":")
                bean.id = arrays[0].trim().toInt()
                bean.status = arrays[1].trim()
                paramBean.plan.add(bean)
            }
        }
        return Gson().toJson(paramBean, WorkDiaryUploadBean::class.java)
    }

    private fun getLocation() {
        RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe {
                    if (it) {
                        LocationObservable.setTime((5 * 60 * 1000).toLong())
                        subscribe = LocationObservable.get()
                                .subscribe({ aMapLocation ->
                                    if (aMapLocation.errorCode == 0) {
                                        location = aMapLocation.address
                                        tv_location.text = aMapLocation.address
                                    }
                                })
                    } else {
                        toast("请开启定位权限")
                    }
                }

    }

    private fun lookOver() {
        val array = arrayOf("自己和领导", "所在部门", "全公司")
        ChooseAlertView.getBottomChoose(this, null, array, { o, pos ->
            tv_look_over.text = array[pos - 1]
            displayType = pos - 1
        }).show()
    }

    private fun initLimit(textView: TextView, listener: OnResultListener) {
        val array = arrayOf("已完成", "未完成", "取消")
        ChooseAlertView.getBottomChoose(this, null, array) { o, pos ->
            textView.text = array[pos - 1]
            listener.callback(array[pos - 1])
        }.show()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == TODAY) {
                    val v = inflater.inflate(R.layout.list_item_130, layout_diary_today, false)
                    val pos = result.getIntExtra(Config.POS, -1)
                    val view = if (pos == -1) {
                        v
                    } else {
                        layout_diary_today.getChildAt(pos)
                    }
                    initItemData(view, result.getStringExtra(Config.START_TIME), result.getStringExtra(Config.END_TIME),
                            result.getStringExtra(Config.CONTENT), result.getStringExtra(Config.RESULT), 0)
                    if (pos == -1)
                        layout_diary_today.addView(view)


                } else if (requestCode == TOMORROW) {
                    val v = inflater.inflate(R.layout.list_item_130, layout_diary_today, false)
                    val pos = result.getIntExtra(Config.POS, -1)
                    val view = if (pos == -1) {
                        v
                    } else {
                        layout_diary_today.getChildAt(pos)
                    }
                    initItemData(view, result.getStringExtra(Config.START_TIME), result.getStringExtra(Config.END_TIME),
                            result.getStringExtra(Config.CONTENT), "", 1)
                    if (pos == -1)
                        layout_diary_tomorrow.addView(view)
                }
            }

            if (resultCode == Config.INTENT_CONTENT && requestCode == 1000) {
                tv_inspiration.text = result.getStringExtra("content")
            }
        }
    }

    private fun initItemData(view: View, startTime: String, endTime: String, content: String, status: String, type: Int) {
        view.tv_time.text = startTime + " - " + endTime
        view.tv_plan.text = content
        view.tv_result.text = status
        if (type == 0) {
            view.tv_plan_label.text = "今日临时事项 :  "
            view.layout_result.visibility = View.VISIBLE
            view.onClick {
                startActivityForResult<WorkDiaryItemActivity>(TODAY, "type" to 0,
                        Config.START_TIME to startTime,
                        Config.END_TIME to endTime,
                        Config.CONTENT to content,
                        Config.RESULT to status,
                        Config.POS to layout_diary_today.indexOfChild(view))
            }
            view.setOnLongClickListener {
                AlertDialog.Builder(this@WorkDiaryAddActivity)
                        .setTitle("提示")
                        .setMessage("是否删除该计划")
                        .setPositiveButton("取消", null)
                        .setNegativeButton("确定", { _, _ ->

                            layout_diary_plan.removeView(view)
                        })
                        .show()
                false
            }
        } else {
            view.tv_plan_label.text = "明日计划事项 :  "
            view.layout_result.visibility = View.GONE
            view.onClick {
                startActivityForResult<WorkDiaryItemActivity>(TODAY, "type" to 1,
                        Config.START_TIME to startTime,
                        Config.END_TIME to endTime,
                        Config.CONTENT to content,
                        Config.POS to layout_diary_today.indexOfChild(view))
            }
            view.setOnLongClickListener {
                AlertDialog.Builder(this@WorkDiaryAddActivity)
                        .setTitle("提示")
                        .setMessage("是否删除该事项")
                        .setPositiveButton("取消", null)
                        .setNegativeButton("确定", { _, _ ->
                            layout_diary_tomorrow.removeView(view)
                        })
                        .show()
                false
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        subscribe?.let {
            if (it.isDisposed) {
                it.dispose()
                subscribe = null
            }
        }
        if (!isUploadSuccess) {
            saveData()
        }

    }


    fun saveData() {
        val bean = SaveDataBean(getParams(), tv_inspiration.text.toString())
        SPUtil.setParam(localClassName + user.uname, bean)
        DataInjector.saveData(this)
    }


    fun clearData() {
        SPUtil.setParam(localClassName + user.uname, Config.NULL)
    }

    data class SaveDataBean(
            val workDiary: String,
            val filling: String
    ) : Serializable


}